package com.neulogistics.contrib.procuredcenter.api.application.integrationevent.handler;

import com.blackto.lib.eventbus.abstraction.IIntegrationEventHandler;
import com.neulogistics.contrib.procuredcenter.api.application.integrationevent.subscribe.CenterReturnOutboundIntegrationEvent;
import com.neulogistics.contrib.procuredcenter.domain.model.aggregate.Goods;
import com.neulogistics.contrib.procuredcenter.domain.model.aggregate.PurchaseOrder;
import com.neulogistics.contrib.procuredcenter.domain.model.enumeration.PurchaseType;
import com.neulogistics.contrib.procuredcenter.domain.model.valueobject.PurchaseItem;
import com.neulogistics.contrib.procuredcenter.domain.repository.IGoodsRepository;
import com.neulogistics.contrib.procuredcenter.domain.repository.IPurchaseOrderRepository;
import com.neulogistics.infrastructure.cache.idservice.RedisIdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

@Component
public class CenterReturnOutboundIntegrationEventHandler implements IIntegrationEventHandler<CenterReturnOutboundIntegrationEvent> {
    @Resource
    RedisIdUtil redisIdUtil;

    @Resource
    IPurchaseOrderRepository purchaseOrderRepository;

    @Resource
    IGoodsRepository goodsRepository;

    private final String PurchaseOrder_Id_Key;

    public CenterReturnOutboundIntegrationEventHandler(@Value("${spring.application.name}") String appName) {
        PurchaseOrder_Id_Key = appName + ":" + "PurchaseOrderId";
    }

    @Override
    public CompletableFuture<Void> handle(CenterReturnOutboundIntegrationEvent event) throws Exception {
        // 生成对应的退货采购单
        Long purchaseOrderId = redisIdUtil.nextId(PurchaseOrder_Id_Key);
        Goods goods = goodsRepository.findById(event.goodsItem.getGoodsId());
        PurchaseItem purchaseItem = event.goodsItem;
        purchaseItem.setGoodsPrice(goods.getGoodsPrice());
        purchaseItem.setVendorId(goods.getVendorInfo().getVendorId());
        purchaseItem.setVendorName(goods.getVendorInfo().getVendorName());

        PurchaseOrder purchaseOrder =
                new PurchaseOrder(purchaseOrderId, PurchaseType.Return, event.warehouseId, purchaseItem);

        purchaseOrderRepository.save(purchaseOrder);
        return CompletableFuture.completedFuture(null);
    }
}
